package com.example.web.demos.config;

import com.example.web.demos.domain.dto.CostModelConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriTemplateHandler;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: scout.du
 * @date: 2022/10/28 18:38
 **/
@Configuration
@Slf4j
public class BeanConfig {


    @Bean
    @ConfigurationProperties
    public CostModelConfig costModelConfig(){
        return new CostModelConfig();
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    public RestTemplate restTemplate1(){
        int timeout = 3000;
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(timeout);
        factory.setReadTimeout(timeout);
        RestTemplate restTemplate = new RestTemplate(factory);
        return restTemplate;
    }

    @Bean
    public UriTemplateHandler uriTemplateHandler(){
        DefaultUriBuilderFactory uriFactory = new DefaultUriBuilderFactory();
        uriFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);  // for backwards compatibility..
        return uriFactory;
    }

//    @Bean
    /*public FilterRegistrationBean threadNameFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        ThreadNameFilter threadNameFilter = new ThreadNameFilter();
        filterRegistrationBean.setFilter(threadNameFilter);
        //配置过滤规则
        filterRegistrationBean.addUrlPatterns("*");
        //执行次序
        filterRegistrationBean.setOrder(Integer.MIN_VALUE);
        return filterRegistrationBean;
    }*/

    @Bean
    public ThreadPoolExecutor getThreadPool() {
        return new ThreadPoolExecutor(16, 16, 60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(10000), (Runnable r, ThreadPoolExecutor executor) -> {
            if (!executor.isShutdown()) {
                try {
                    executor.getQueue().put(r);
                } catch (InterruptedException e) {
                    log.error("sync to pdc repository error");
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

}